import React, { useEffect, useMemo, useState } from 'react';
import { Form, Button, message } from 'antd';
import FormRender from '@/components/FormRender';
import useGetDeptList from '@/components/_hooks/useGetDeptList';
import useAdminPermission from '@/components/_hooks/useAdminPermission';
import { getDispatchInfo, setDispatchInfo } from '@/api';
import dayjs from 'dayjs';

/**
 * 派单设置
 */

export default function DispatchSetting() {
  const [form] = Form.useForm();
  const deptList = useGetDeptList();
  const isAdmin = useAdminPermission();
  const [noFollowUpRecovery, setNoFollowUpRecovery] = useState(false)

  useEffect(() => {
    getDispatchInfo()
      .then((data) => {
        if (!data) return;
        form?.setFieldsValue({
          ...data,
          workTime: [
            dayjs(data?.workStartTime, 'HH:mm'),
            dayjs(data?.workEndTime, 'HH:mm'),
          ],
        });
        setNoFollowUpRecovery(data?.noFollowUpRecovery)
      })
      .catch((err) => {
        throw err;
      });
  }, []);

  const formItemList = useMemo(() => {
    return [
      {
        title: '',
        Items: [
          // {
          //   label: '自动派单',
          //   name: 'autoDispatch',
          //   type: 'radio',
          //   rules: [
          //     { required: true }
          //   ]
          // },
          {
            label: '接单部门',
            name: 'receiveDept',
            type: 'select',
            items: deptList,
            disabled: !isAdmin,
            mode: 'multiple',
            // initValue: undefined,
            rules: [{ required: true }],
          },
          {
            label: '接单时间',
            name: 'workTime',
            type: 'timeRange',
            disabled: !isAdmin,
            format: 'HH:mm',
            rules: [{ required: true }],
          },
          {
            label: '自动接单',
            name: 'autoReceive',
            disabled: !isAdmin,
            type: 'radio',
          },
          {
            label: '超期自动回收',
            name: 'noFollowUpRecovery',
            disabled: !isAdmin,
            type: 'radio',
          },
          {
            label: '超期时间',
            name: 'noFollowUpRecoveryDay',
            disabled: !isAdmin,
            type: 'input',
            addonAfter: "天",
            unenabled: !noFollowUpRecovery,
            rules: [
              { required: true },
              {
                pattern: /^[1-9]\d*$/,
                message: '请输入正整数'
              }
            ]
          }
        ],
      },
    ]
  }, [noFollowUpRecovery, deptList])

  const submit = async () => {
    const values = await form.validateFields();
    if (!values) return;
    const { workTime, noFollowUpRecoveryDay, ...rest } = values;
    let params = { ...rest, ...{ noFollowUpRecoveryDay: noFollowUpRecoveryDay ?? null } };
    if (workTime) {
      params = {
        ...params,
        workStartTime: `${dayjs(workTime?.[0]).format('HH:mm:ss')}`,
        workEndTime: `${dayjs(
          workTime?.[1]
        ).format('HH:mm:ss')}`,
      };
    }
    setDispatchInfo(params)
      .then((res) => {
        if (res) return message.success('保存成功');
      })
      .catch((info) => {
        console.log('Validate Failed:', info);
      });
  };
  const onValuesChange = (changedValues: { [key: string]: boolean }) => {
    if (changedValues?.noFollowUpRecovery !== undefined) {
      setNoFollowUpRecovery(changedValues?.noFollowUpRecovery)
    }
  }

  return (
    <div>
      <FormRender
        form={form}
        formItem={formItemList}
        layout={{
          labelCol: { span: 6 },
          wrapperCol: { span: 8 },
        }}
        onValuesChange={onValuesChange}
      />
      <Button type='primary' disabled={!isAdmin} onClick={submit} style={{ marginLeft: '40%' }}>
        保存
      </Button>
    </div>
  );
}

DispatchSetting.route = {
  [MENU_PATH]: '/operate/dispatch',
};
